package cn.springcloud.fix.demo.thread;

import lombok.Data;

public class ReadWriteTest {

    public static void main(String[] args) {
        Unng unng = new Unng();
        new Thread(new ReadThread(unng)).start();
        new Thread(new WriteThread(unng)).start();
    }

    static class ReadThread implements Runnable {

        private Unng unng;

        public ReadThread(Unng unng) {
            this.unng = unng;
        }

        @Override
        public void run() {
            while (unng.content < 100) {
                synchronized (unng) {
                    if (!unng.readAble) {
                        try {
                            unng.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("读了：" + unng.content);
                    unng.readAble = false;
                    unng.notify();
                }
            }
        }
    }

    static class WriteThread implements Runnable {

        private Unng unng;

        public WriteThread(Unng unng) {
            this.unng = unng;
        }

        @Override
        public void run() {
            while (unng.content < 100) {
                synchronized (unng) {
                    if (unng.readAble) {
                        try {
                            unng.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    unng.content++;
                    System.out.println("写了：" + unng.content);
                    unng.readAble = true;
                    unng.notify();
                }
            }
        }
    }

    @Data
    static class Unng {
        private boolean readAble;
        private int content;
    }
}
